<template>
  <div class="commentparent">
    <div v-for="(item, index) in commentList" :key="index">
      <div class="commentItem">
        <div class="userImg">
          <img
            :src="item.userinfo.user_img"
            alt=""
            v-if="item.userinfo && item.userinfo.user_img"
          />
          <img src="~images/head_img.png" alt="" v-else />
        </div>
        <div class="commnetcontent">
          <p>
            <span v-if="item.userinfo">{{ item.userinfo.name }}</span>
            <span v-else>无名</span>
            <span>{{ item.comment_date }}</span>
          </p>
          <div>
            {{ item.comment_content
            }}<span class="publish" @click="publishClick(item.comment_id)"
              >回复</span
            >
          </div>
        </div>
      </div>
      <div style="padding-left: 40px">
        <comment-item
          @postPublish="publishClick"
          :commentChild="item.child"
        ></comment-item>
      </div>
    </div>
  </div>
</template>

<script>
  import commentItem from './commentItem'
  export default {
    data() {
      return {
        commentList: null,
      }
    },
    components: {
      commentItem,
    },
    methods: {
      async commentData() {
        const res = await this.$http.get('/comment/' + this.$route.params.id)
        if (res.data) {
          this.$emit('lengthselect', res.data.length)
        }
        this.commentList = this.changeCommentData(res.data)
      },
      changeCommentData(data) {
        function fn(temp) {
          let arr = []
          for (var i = 0; i < data.length; i++) {
            if (data[i].parent_id == temp) {
              arr.push(data[i])
              data[i].child = fn(data[i].comment_id)
            }
          }
          return arr
        }
        return fn(null)
      },
      publishClick(id) {
        this.$emit('publishClick', id)
      },
    },
    created() {
      this.commentData()
    },
  }
</script>

<style lang="stylus" scoped>
  .commentparent
    padding: 10px 10px

    >div
      border-bottom: 1px solid #e7e7e7

    .commentItem
      display: flex
      padding: 10px 0

      .userImg
        margin-right: 10px

        img
          border-radius: 50%
          width: 35px
          height: 35px

      .commnetcontent
        margin-bottom: 10px
        position: relative
        flex: 1

        p
          color: #555
          font-size: 13px
          display: flex
          justify-content: space-between
          margin-bottom: 5px

        div
          font-size: 13px

        .publish
          position: absolute
          color: #999999
          right: 0
</style>